package coba.mailing.mail;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import coba.mailing.body.Body5;
import coba.mailing.function.NextXday;
import coba.mailing.jdbc.ConnectionFactory;
import coba.mailing.model.Atractivo;
import coba.mailing.model.Itinerario;
import coba.mailing.model.Solicitud;
import coba.mailing.procedure.AddAllCC;
import coba.mailing.procedure.AddAllTo;
import coba.mailing.properties.MainProperties;
import coba.mailing.query.FindAllItinerario;
import coba.mailing.query.FindAtractivoByItinerarioIdQuery;
import coba.mailing.query.FindSolicitudWhereFechaItinerarioBetween;

public class Mail5 {

	public static void send() throws ClassNotFoundException, IOException, SQLException, EmailException {
		MainProperties mainProperties = MainProperties.getInstance();
		
		Connection con = ConnectionFactory.getConnection();

		Calendar today0Hour = GregorianCalendar.getInstance();

		today0Hour.set(Calendar.HOUR_OF_DAY, 0);
		today0Hour.set(Calendar.MINUTE, 0);
		today0Hour.set(Calendar.SECOND, 0);
		today0Hour.set(Calendar.MILLISECOND, 0);

		Date mondayNextWeek = NextXday.nextXday(Calendar.MONDAY, today0Hour.getTime());
		Date saturdayNextWeek = NextXday.nextXday(Calendar.SATURDAY, mondayNextWeek);

		/*
		 * Solicitudes de la proxima semana
		 */
		List<Solicitud> listSolicitud = FindSolicitudWhereFechaItinerarioBetween.find(con, mondayNextWeek, saturdayNextWeek);

		/*
		 * Set de recorridos y hora de comienzo
		 */
		/*
		List<Itinerario> listItinerario = FindAllItinerario.find(con);

		List<Atractivo> listAllAtractivos = new LinkedList<Atractivo>();
		Set<String> setRecorridoIdHoraComienzo = new HashSet<String>();
		Map<String, AtractivoSum> mapRecorridoIdHoraComienzoAtractivoSum = new HashMap<String, AtractivoSum>();

		for (Itinerario itinerario : listItinerario) {
			List<Atractivo> listAtractivo = FindAtractivoByItinerarioIdQuery.find(con, itinerario.getItinerarioId());
			listAllAtractivos.addAll(listAtractivo);
			List<AtractivoSum> listAtractivoSum = SumAtractivos.sumAtractivos(listAtractivo);

			for (AtractivoSum it : listAtractivoSum) {
				setRecorridoIdHoraComienzo.add(it.getRecorridoId() + "-" + it.getHoraComienzo());
				mapRecorridoIdHoraComienzoAtractivoSum.put(it.getRecorridoId() + "-" + it.getHoraComienzo(), it);
			}
		}
		*/

		/*
		 * Por cada recorridoId - HoraComienzo
		 */
		/*
		for (String it : setRecorridoIdHoraComienzo) {

			Set<Long> setDias = new HashSet<Long>();

			Long recorridoId = Long.valueOf(it.split("-")[0]);
			Long horaComienzo = Long.valueOf(it.split("-")[1]);

			for (Solicitud solicitud : listSolicitud) {
				//System.err.println("Recorridoid: " + recorridoId);
				//System.err.println("horaComienzo: " + horaComienzo);
				for (Atractivo atractivo : listAllAtractivos) {
					//System.err.println("atractivo.getRecorridoId: " + atractivo.getRecorridoId());
					//System.err.println("atractivo.getHora: " + atractivo.getHora());
					if (atractivo.getItinerarioId().equals(solicitud.getItinerarioId())) {
						if (atractivo.getRecorridoId().equals(recorridoId)) {
							System.err.println("hora1: " + horaComienzo);
							System.err.println("hora2: " + atractivo.getHora());
							if (atractivo.getHora().equals(horaComienzo)) {
								System.err.println("PK!!!");
								Calendar calFechaItinerario = GregorianCalendar.getInstance();
								calFechaItinerario.setTime(solicitud.getFechaItinerario());

								setDias.add(Long.valueOf(calFechaItinerario.get(Calendar.DAY_OF_WEEK)));
							}
						}
					}
						//System.err.println("atractivo.getRecorridoId: " + atractivo.getRecorridoId());
						//System.err.println("atractivo.getHora: " + atractivo.getHora());					}
				}
			}

			// enviar mail

		}
		*/

		/*
		 * Version simplificada, solo polideportivo...
		 */
		List<Itinerario> listItinerario = FindAllItinerario.find(con);
		List<Atractivo> listAllAtractivos = new LinkedList<Atractivo>();

		for (Itinerario itinerario : listItinerario) {
			listAllAtractivos.addAll(FindAtractivoByItinerarioIdQuery.find(con, itinerario.getItinerarioId()));
		}

		Set<Long> setDias = new HashSet<Long>();
		for (Solicitud solicitud : listSolicitud) {
			for (Atractivo atractivo : listAllAtractivos) {
				if (atractivo.getItinerarioId().equals(solicitud.getItinerarioId())) {
					if (atractivo.getRecorridoId().equals(Long.valueOf(mainProperties.getProperty("polideportivoId")))) {
						Calendar calFechaItinerario = GregorianCalendar.getInstance();
						calFechaItinerario.setTime(solicitud.getFechaItinerario());

						setDias.add(Long.valueOf(calFechaItinerario.get(Calendar.DAY_OF_WEEK)));
					}
				}
			}
		}

		if (!setDias.isEmpty())
			send(mondayNextWeek, saturdayNextWeek, setDias);

		con.close();
	}

	public static void send(Date monday, Date saturday, Set<Long> setDias) throws EmailException, IOException {
		MainProperties mainProperties = MainProperties.getInstance();

		HtmlEmail email = new HtmlEmail();

		email.setCharset("utf-8");
		email.setHostName(mainProperties.getProperty("smtpServer"));
		email.setSmtpPort(Integer.valueOf(mainProperties.getProperty("smtpPort")));

		email.setFrom(mainProperties.getProperty("fromMail"), mainProperties.getProperty("fromName"));

		AddAllTo.addAllTo(email, mainProperties.getProperty("mail5Tos"));
		AddAllCC.addAllCC(email, mainProperties.getProperty("mail5Ccs"));

		email.setSubject(subject(monday, saturday));

		String cid = email.embed(ClassLoader.getSystemClassLoader().getResource("coba-mail-footer.jpg"), "Conociendo footer");

		email.setHtmlMsg(Body5.get(cid, setDias));

		email.send();
	}

	private static String subject(Date monday, Date saturday) {

		String[] arrMes = { "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio",
				"Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre" };

		StringBuilder subject = new StringBuilder("ConociendoBA - Semana del ");
		
		Calendar calMonday = GregorianCalendar.getInstance();
		calMonday.setTime(monday);

		subject.append(calMonday.get(Calendar.DAY_OF_MONTH));

		subject.append(" al ");

		Calendar calSaturday = GregorianCalendar.getInstance();
		calSaturday.setTime(saturday);

		subject.append(calSaturday.get(Calendar.DAY_OF_MONTH));

		subject.append(" de ");

		subject.append(arrMes[calSaturday.get(Calendar.MONTH)]);

		return subject.toString();
	}

}
